package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"log"
)

// 模拟从数据库读取密钥字符串
func getPrivateKeyFromDB() string {
	// 这里返回从数据库中读取的私钥字符串
	return `-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA2umPYz1Uh78GBMQMvrXGyoxsBATNewuM+sNE/GP6CBN5mKgl
+wRLteZXN2SYlipd1nwQ79rQDPmFZOQTSbQLqqacj8rfnFX1XnAVHqahdSDez8/n
SrFkX6BpLVvVzDHzZuTnTpnker8z4f5/D0xggTw5qtwFmqXfoLRDcZqb+P8Gy0yW
457/2mWC5dCpEryVW6xexR0r0nIhhGcFgcXlOF/TxxNTIarYwX4MX2u/DvOU5K6R
uYl5Z3+0jnVaj5T7Kz1puybIaqsqX4nR1y8tG/uUjW4/zUP7+4+In9uDf/2MUKlD
a65TL55UczWi4sMSTztO5yB+ux3tLv6j6nbgbwIDAQABAoIBAB8N/QJWA/TR23e3
nBs9zDqVmwki6UdoRxKXuuSXBjQ5FwnZ6LFoVZkzWPIJuj+rOO6hYQG1p8f/abX7
SOUuvmzx/8nCPOB/rTQ9cDGN79+ezxzp4GTPL28FYYZGvdieyWmyVUHoQOpMz35i
zQGNky8iLQgY+E6M82Fn0R1/klrLB6q+u/3DViqq1B4LQAShoqMSHgIOxMFXmNr5
MKdk6HFVYD7LqA1xYlas94ACwNF9+gk9RYCpWQM8mvB2J4/GZr7k65wjjxP8unB6
S1o0G6kLfnpMbbGr30gg6/k0owVtw+BH4xHE6XrvEDSg+1IOriTkFe2yimqVN0u5
m5JfCbkCgYEA5s389G/FJTxIEvLElW6YY6E4C/6HObDh2SqFajWOjmSWxTWFexds
b1o4xheIAujBeAK5Q1WtFuotK50ZfizUy4sOUiAik3ZxMHSRYn7b0T6fpOPkVKMG
T80PUswmczK/tcwNqos/MFwRB+rOLwT46SKGlV5llGbsBO0zER5fkO0CgYEA8s87
kXoQpu7Si8OXyp6dwdvOlVo2Cz2c43jNfP4G011qA9o5QhrkEqoCRnJXv3Jdha2F
i6/A6bqnsr2Bo6n8nNoZ0hqHqBfyGJ1TsXHWrj9ayvZ566hr9iSG+zMoLzj7Klz2
e6u0IkCbLFMP6vUcykVKAEeKQas+4UO5sc2Wt0sCgYEApNpYZNc4fyIRcMdJtloq
Km9KsvZ367L1fcGrTXM3gWlDb1SNJKBUaSyOBJ9mHH3XQjrfzMJzQTy+SrqJLOAk
lcWa0vn0+FLPAgcgmLN3mnsaWBIWUoWmynTzDvaWOA31dIps8HVJCueXmooR/u+U
QiDQ8/tanqbsyZAKu51wMPkCgYBAotXyphHkvlKiDhFMSOkp//+AVqFoYKBxFWlu
Spk6jvV3zRHM/SeVqFgutKWTOziWK1kPlFvAXIXj2Pq3vLqYbp7NBW7zWlyCHO94
nxtNC2R5/x75kr4aqiKcoEOkPoDuCA09YrnzHEuygvIL0/A0EDng1SqCzLlSchru
sBHc/QKBgCQL+nughyWXnun4jXlAj6UOI1TN7exO4to1U/rBJu6zodmnyBBZVaL2
rx1BmRhMmP+J4FXrbChdzp1s4MUOs0xPnfM3FnZO0cJHF1ULwA4+odzzhFxg+IWS
ZguiRmGAUo1InaPA5Cbj0OyN9G/aLqN71qW8803hqWn/n2LLnu2x
-----END RSA PRIVATE KEY-----`
}

func getPublicKeyFromDB() string {
	// 这里返回从数据库中读取的公钥字符串
	return `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2umPYz1Uh78GBMQMvrXG
yoxsBATNewuM+sNE/GP6CBN5mKgl+wRLteZXN2SYlipd1nwQ79rQDPmFZOQTSbQL
qqacj8rfnFX1XnAVHqahdSDez8/nSrFkX6BpLVvVzDHzZuTnTpnker8z4f5/D0xg
gTw5qtwFmqXfoLRDcZqb+P8Gy0yW457/2mWC5dCpEryVW6xexR0r0nIhhGcFgcXl
OF/TxxNTIarYwX4MX2u/DvOU5K6RuYl5Z3+0jnVaj5T7Kz1puybIaqsqX4nR1y8t
G/uUjW4/zUP7+4+In9uDf/2MUKlDa65TL55UczWi4sMSTztO5yB+ux3tLv6j6nbg
bwIDAQAB
-----END PUBLIC KEY-----`
}

// 解析私钥
func parsePrivateKey(pemString string) (*rsa.PrivateKey, error) {
	block, _ := pem.Decode([]byte(pemString))
	if block == nil {
		return nil, fmt.Errorf("failed to parse PEM block containing the key")
	}
	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("failed to parse private key: %v", err)
	}
	return privateKey, nil
}

// 解析公钥
func parsePublicKey(pemString string) (*rsa.PublicKey, error) {
	block, _ := pem.Decode([]byte(pemString))
	if block == nil {
		return nil, fmt.Errorf("failed to parse PEM block containing the key")
	}
	publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("failed to parse public key: %v", err)
	}
	rsaPublicKey, ok := publicKey.(*rsa.PublicKey)
	if !ok {
		return nil, fmt.Errorf("public key is not of type *rsa.PublicKey")
	}
	return rsaPublicKey, nil
}

// RSA公钥加密
func rsaEncrypt(publicKey *rsa.PublicKey, plaintext []byte) ([]byte, error) {
	ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plaintext)
	if err != nil {
		return nil, fmt.Errorf("failed to encrypt: %v", err)
	}
	return ciphertext, nil
}

// RSA私钥解密
func rsaDecrypt(privateKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) {
	plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)
	if err != nil {
		return nil, fmt.Errorf("failed to decrypt: %v", err)
	}
	return plaintext, nil
}

func main() {
	// 从数据库获取密钥字符串
	privateKeyPEM := getPrivateKeyFromDB()
	publicKeyPEM := getPublicKeyFromDB()
	//解析私钥和公钥
	privateKey, err := parsePrivateKey(privateKeyPEM)
	if err != nil {
		log.Fatalf("Failed to parse private key: %v", err)
	}
	publicKey, err := parsePublicKey(publicKeyPEM)
	if err != nil {
		log.Fatalf("Failed to parse public key: %v", err)
	}

	// 要加密的明文数据
	plaintext := []byte("Hello, RSA!")

	// 公钥加密
	ciphertext, err := rsaEncrypt(publicKey, plaintext)
	if err != nil {
		log.Fatalf("Failed to encrypt: %v", err)
	}
	fmt.Printf("Ciphertext: %x\n", string(ciphertext))

	// 私钥解密
	decryptedText, err := rsaDecrypt(privateKey, ciphertext)
	if err != nil {
		log.Fatalf("Failed to decrypt: %v", err)
	}
	fmt.Printf("Decrypted Text: %s\n", decryptedText)
}
